#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    ui->lineEdit->setPlaceholderText("输入要添加的元素");

    ui->treeWidget->setHeaderLabel("动物");

    QTreeWidgetItem* item1 = new QTreeWidgetItem();
    item1->setText(0, "猫");
    ui->treeWidget->addTopLevelItem(item1);

    QTreeWidgetItem* item2 = new QTreeWidgetItem();
    item2->setText(0, "狗");
    ui->treeWidget->addTopLevelItem(item2);

    QTreeWidgetItem* item3 = new QTreeWidgetItem();
    item3->setText(0, "鸟");
    ui->treeWidget->addTopLevelItem(item3);
}

Widget::~Widget()
{
    delete ui;
}


void Widget::on_pushButton_clicked()
{
    // 获取输入框内容
    const QString& text = ui->lineEdit->text();
    if(text.isEmpty())
    {
        return;
    }

    // 构造新节点并添加到顶层
    QTreeWidgetItem* newItem = new QTreeWidgetItem();
    newItem->setText(0, text);
    ui->treeWidget->addTopLevelItem(newItem);
    ui->lineEdit->clear();
}

void Widget::on_pushButton_2_clicked()
{
    // 获取输入框内容
    const QString& text = ui->lineEdit->text();
    if(text.isEmpty())
    {
        return;
    }

    // 获取当前选中的节点
    QTreeWidgetItem* current = ui->treeWidget->currentItem();
    if(current == nullptr)
    {
        return;
    }

    // 构造新节点并添加到选中节点下
    QTreeWidgetItem* child = new QTreeWidgetItem();
    child->setText(0, text);
    current->addChild(child);
    ui->lineEdit->clear();
    current->setExpanded(true);
}

void Widget::on_pushButton_3_clicked()
{
    // 获取当前选中节点
    QTreeWidgetItem* current = ui->treeWidget->currentItem();
    if(current == nullptr)
    {
        return;
    }

    // 获取当前节点父节点进行判断
    QTreeWidgetItem* parent = current->parent();
    if(parent == nullptr)
    {
        int index = ui->treeWidget->indexOfTopLevelItem(current);
        ui->treeWidget->takeTopLevelItem(index);
    }
    else
    {
        parent->removeChild(current);
    }
}
